Imports System.Data.SqlClient
Imports System.Drawing
Imports DevExpress.XtraGrid
Imports DevExpress.XtraGrid.Views.Base
Imports DevExpress.XtraGrid.Columns
Imports DevExpress.XtraEditors
Imports DevExpress.XtraScheduler
Imports DevExpress.XtraScheduler.UI
Imports DevExpress.XtraEditors.Repository
Imports DevExpress.XtraGrid.Views.Grid

'--- Created Date On : 18-Nov-2010 (Jagdish)

Public Class frmInventoryAdjustment
    Dim mstrMode As String
    Public blnAdd As Boolean, blnEdit As Boolean, blnDelete As Boolean, blnLocked As Boolean
    Dim mlngRecordID As Long
    Dim blnUnload As Boolean
    Dim mblnChanged As Boolean
    Dim mblnActivate As Boolean
    Dim mblnExpanded As Boolean = False
    Dim mblnAutoSize As Boolean = True
    Dim mblnCancelDisplay As Boolean
    Dim mblnPopulateData As Boolean = False
    Dim WithEvents rpGlkItemName As RepositoryItemGridLookUpEdit
    Dim WithEvents rpTxtQuantity As RepositoryItemTextEdit
    Dim WithEvents rpCmbType As RepositoryItemComboBox
    Dim WithEvents rpDtDate As RepositoryItemDateEdit
    Dim WithEvents GLKEdit As GridLookUpEdit
    Dim ItemDetailsDataRow As DataRow

    Private Sub frmInventoryAdjustment_Activated(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Activated
        Try
            If mblnActivate = True Then
                mblnActivate = False

                pbRecords.Visible = True
                pbRecords.BringToFront()
                Application.DoEvents()
                pbRecords.Position = 20

                Call PopulateLookUpName()
                glkSelectItem.EditValue = 0
                chkDateRange.Checked = True
                dtFromDate.DateTime = Format(DateAdd(DateInterval.Day, 1, DateAdd(DateInterval.Month, -1, gdtCurrentDate)), gstrDtFormat)
                dtToDate.DateTime = Format(gdtCurrentDate, gstrDtFormat)
                mblnPopulateData = True
                Call SetEditorDataColumn()
                Call PopulateData()

                pbRecords.Position = 100
                pbRecords.Visible = False
            End If

        Catch ex As Exception
            pbRecords.Visible = False
            MessageBox.Show(ex.Message, gstrMessage, MessageBoxButtons.OK, MessageBoxIcon.Error)
            AddErrorLog("Error " & Err.Number & " (" & Err.Description & ") in Procedure " & _
                Reflection.MethodBase.GetCurrentMethod.Name & " Of " & Me.Name)
        End Try
    End Sub
    Private Sub InitialiseDataEntry()
        Dim dtTemp As DataTable
        dtTemp = New DataTable("Diagnosis")
        With dtTemp.Columns
            .Add("ID", GetType(Integer))
            .Add("Date", GetType(Date))
            .Add("Item Name", GetType(Integer))
            .Add("Item#", GetType(String))
            .Add("Manufacturer", GetType(String))
            .Add("Category", GetType(String))
            .Add("Calculated Quantity", GetType(Integer))
            .Add("Type", GetType(String))
            .Add("Physical Qty", GetType(Integer))
        End With
        grdDataEntry.DataSource = dtTemp
        gdvDataEntry.Columns("ID").Visible = False
        dtTemp.Dispose()
    End Sub

    Private Sub SetEditorDataColumn()
        Try
            Call InitialiseDataEntry()
            Dim fnBold As New System.Drawing.Font("Tahoma", 8.25!, System.Drawing.FontStyle.Bold)
            With gdvDataEntry
                .Columns("ID").Visible = False
                .Columns("ID").OptionsColumn.ShowInCustomizationForm = False

                .Columns("Date").AppearanceHeader.Font = fnBold
                .Columns("Date").Width = 100

                .Columns("Item Name").AppearanceHeader.Font = fnBold
                .Columns("Item Name").Width = 100

                .Columns("Item#").OptionsColumn.AllowEdit = False
                .Columns("Item#").OptionsColumn.AllowFocus = False

                .Columns("Manufacturer").OptionsColumn.AllowEdit = False
                .Columns("Manufacturer").OptionsColumn.AllowFocus = False

                .Columns("Category").OptionsColumn.AllowEdit = False
                .Columns("Category").OptionsColumn.AllowFocus = False

                .Columns("Calculated Quantity").OptionsColumn.AllowEdit = False
                .Columns("Calculated Quantity").OptionsColumn.AllowFocus = False


                .Columns("Type").AppearanceHeader.Font = fnBold
                .Columns("Type").Width = 100

                .Columns("Physical Qty").AppearanceHeader.Font = fnBold
                .Columns("Physical Qty").Width = 100
                .Columns("Physical Qty").DisplayFormat.FormatType = DevExpress.Utils.FormatType.Custom
                .Columns("Physical Qty").DisplayFormat.FormatString = "0"

                .OptionsNavigation.EnterMoveNextColumn = True
            End With
            rpGlkItemName = New RepositoryItemGridLookUpEdit()
            Dim DiagnosisNameSize As Size
            DiagnosisNameSize.Width = 500
            DiagnosisNameSize.Height = 40
            Dim dsTemp As DataSet = FillDataSet("Select ItemId,ItemName,ItemCode,Category,ManufacturerName,QOH from vwItemDetails Order by ItemName")
            With rpGlkItemName
                .Buttons.AddRange(New DevExpress.XtraEditors.Controls.EditorButton() {New DevExpress.XtraEditors.Controls.EditorButton(DevExpress.XtraEditors.Controls.ButtonPredefines.OK, "Refresh list")})
                .DataSource = dsTemp.Tables(0)
                .DisplayMember = "ItemName"
                .ValueMember = "ItemId"
                .NullText = ""
                .ImmediatePopup = True
                .ShowFooter = False
                .View.FocusRectStyle = DrawFocusRectStyle.RowFocus
                .View.OptionsSelection.EnableAppearanceFocusedCell = False
                .View.OptionsView.AutoCalcPreviewLineCount = True
                .View.OptionsFilter.AllowColumnMRUFilterList = True
                .View.OptionsFilter.AllowFilterEditor = True
                .View.OptionsFilter.AllowMRUFilterList = True
                .View.OptionsView.ShowAutoFilterRow = True
                .View.OptionsView.ShowIndicator = False
                .View.OptionsView.ShowGroupPanel = False
                .View.OptionsView.ShowPreview = True
                .View.OptionsFilter.ShowAllTableValuesInFilterPopup = True
                .TextEditStyle = DevExpress.XtraEditors.Controls.TextEditStyles.Standard
                .ImmediatePopup = True
                .ShowFooter = False
                .View.Columns("ItemId").Visible = False
                .PopupFormMinSize = DiagnosisNameSize

            End With
            dsTemp.Dispose()


            rpTxtQuantity = New RepositoryItemTextEdit
            With rpTxtQuantity
                .Mask.MaskType = DevExpress.XtraEditors.Mask.MaskType.Numeric
                .Mask.EditMask = "n0"
                .Mask.UseMaskAsDisplayFormat = True
            End With


            rpCmbType = New RepositoryItemComboBox
            With rpCmbType
                .Items.Add("Deficit")
                .Items.Add("Excess")
            End With

            rpDtDate = New RepositoryItemDateEdit
            With rpDtDate
                .Mask.MaskType = Mask.MaskType.DateTime
                .Mask.EditMask = gstrDtFormat
                .DisplayFormat.FormatType = DevExpress.Utils.FormatType.DateTime
                .DisplayFormat.FormatString = gstrDtFormat
                .EditFormat.FormatType = DevExpress.Utils.FormatType.DateTime
                .EditFormat.FormatString = gstrDtFormat
            End With
            grdDataEntry.RepositoryItems.AddRange(New DevExpress.XtraEditors.Repository.RepositoryItem() {rpDtDate, rpGlkItemName, rpTxtQuantity, rpCmbType})
            With gdvDataEntry
                .Columns("Date").ColumnEdit = rpDtDate
                .Columns("Item Name").ColumnEdit = rpGlkItemName
                .Columns("Physical Qty").ColumnEdit = rpTxtQuantity
                .Columns("Type").ColumnEdit = rpCmbType
                .OptionsView.ShowFooter = True
                .Columns("Item Name").SummaryItem.SetSummary(DevExpress.Data.SummaryItemType.Count, "Total {0} records")
            End With
        Catch ex As Exception
            MessageBox.Show(ex.Message, gstrMessage, MessageBoxButtons.OK, MessageBoxIcon.Error)
            Call AddErrorLog("Error " & Err.Number & " (" & Err.Description & ") in Procedure " & _
                 Reflection.MethodBase.GetCurrentMethod.Name & " Of " & Me.Name)
        End Try
    End Sub

    Private Sub PopulateLookUpName()
        Dim dsTemp As DataSet = FillDataSet("select ItemId,ItemName,ItemCode [Item#]" & _
                                            ",Category from vwItemDetails Union all " & _
                                            "Select 0 [ItemId],'<---All Items--->' [ItemName],'' [Item#],'' [Category] Order by Category,ItemName ")
        With glkSelectItem.Properties
            .DataSource = dsTemp.Tables(0)
            .DisplayMember = "ItemName"
            .ValueMember = "ItemId"
            .NullText = ""
            .ImmediatePopup = True
            .ShowFooter = False
            .View.OptionsSelection.EnableAppearanceFocusedCell = False
            .View.OptionsView.AutoCalcPreviewLineCount = True
            .View.OptionsFilter.AllowColumnMRUFilterList = True
            .View.OptionsFilter.AllowFilterEditor = True
            .View.OptionsFilter.AllowMRUFilterList = True
            .View.OptionsView.ShowAutoFilterRow = True
            .View.OptionsView.ShowIndicator = False
            .View.OptionsView.ShowGroupPanel = False
            .View.OptionsView.ShowPreview = True
            .View.OptionsFilter.ShowAllTableValuesInFilterPopup = True
            .ImmediatePopup = True
            .ShowFooter = False
            .View.Columns("ItemId").Visible = False
        End With
    End Sub

    Private Sub PopulateData()
        Dim dsRecords As DataSet   'For populating data in XtraGrid
        Dim strQuery As String = ""

        Try
            pbRecords.Position = 40 : Application.DoEvents()

            If chkDateRange.Checked = True And (IsDBNullOrNothing(dtFromDate.EditValue) Or IsDBNullOrNothing(dtToDate.EditValue)) Then
                Exit Sub
            End If

            strQuery = "Select A.AdjustmentId [ID],A.DtDate [Date],A.ItemId [Item Name],I.ItemCode [Item#], " & _
                        "I.ManufacturerName [Manufacturer],I.Category [Category],I.QOH [Calculated Quantity], " & _
                        "(Case When A.Type=0 Then 'Deficit' Else 'Excess' End) [Type],A.Qty [Physical Qty] from tblInventoryAdjustment A " & _
                        "Inner Join vwItemDetails I On A.ItemId=I.ItemId "
                      
            If chkDateRange.Checked = True Then
                strQuery = strQuery & " and A.DtDate Between '" & Format(CDate(dtFromDate.EditValue), gstrDtFormat) & _
                          "' And '" & Format(CDate(dtToDate.EditValue), gstrDtFormat) & "'"
            End If
            If Val(glkSelectItem.EditValue) > 0 Then
                strQuery = strQuery & " and A.ItemId=" & Val(glkSelectItem.EditValue)
            End If

            strQuery = strQuery & " Order by A.AdjustmentId"

            dsRecords = FillDataSet(strQuery)

            dsRecords.Tables(0).Rows.Add()
            Dim dt As Date
            Dim dsTemp As DataSet = FillDataSet("Select top 1 DtDate from tblInventoryAdjustment where AdjustmentId>0 order by AdjustmentId desc")
            With dsTemp.Tables(0)
                If .Rows.Count > 0 Then
                    If IsDBNullOrNothing(.Rows(0).Item("DtDate")) Then
                        dt = Date.Now
                    Else
                        dt = .Rows(0).Item("DtDate")
                    End If
                Else
                    dt = Date.Now
                End If
            End With
            'Dim dt As String = strRecordID("tblInventoryAdjustment", " IsNull(DtDate,'')", "AdjustmentId > 0 order by AdjustmentId desc")
            If IsDBNullOrNothing(dt) Then
                dsRecords.Tables(0).Rows(dsRecords.Tables(0).Rows.Count - 1).Item("Date") = Date.Now
            Else
                dsRecords.Tables(0).Rows(dsRecords.Tables(0).Rows.Count - 1).Item("Date") = CDate(dt)
            End If
            '
            'gdvDataEntry.Columns.Clear()
            With grdDataEntry
                .BeginUpdate()
                .DataSource = dsRecords.Tables(0)
                .EndUpdate()
            End With
            dsRecords.Dispose()

            With gdvDataEntry
                'Primary Key Field
                .Columns("ID").Visible = False
                .Columns("ID").OptionsColumn.ShowInCustomizationForm = False
                .BestFitColumns()
            End With
            pbRecords.Position = 80 : Application.DoEvents()

        Catch ex As Exception
            MessageBox.Show(ex.Message, gstrMessage, MessageBoxButtons.OK, MessageBoxIcon.Error)
            AddErrorLog("Error " & Err.Number & " (" & Err.Description & ") in Procedure " & _
                Reflection.MethodBase.GetCurrentMethod.Name & " Of " & Me.Name)
        End Try
    End Sub

    Private Sub frmInventoryAdjustment_FormClosing(ByVal sender As Object, ByVal e As System.Windows.Forms.FormClosingEventArgs) Handles Me.FormClosing
        Try

            Dim intUnload As DialogResult

            If mblnChanged = True Then
                intUnload = MessageBox.Show("You have not saved your changes to the record. Do you want to save your changes now?", gstrMessage, MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question, MessageBoxDefaultButton.Button1)
                If intUnload = Windows.Forms.DialogResult.Cancel Then
                    e.Cancel = True : Exit Sub
                ElseIf intUnload = Windows.Forms.DialogResult.Yes Then
                    blnUnload = True
                    If blnSaveRecords() = False Then
                        e.Cancel = True
                        blnUnload = False
                        Exit Sub
                    End If
                    mblnChanged = False
                End If
            End If
            blnUnload = False

        Catch ex As Exception
            blnUnload = False
            MessageBox.Show(ex.Message, gstrMessage, MessageBoxButtons.OK, MessageBoxIcon.Error)
            AddErrorLog("Error " & Err.Number & " (" & Err.Description & ") in Procedure " & _
                Reflection.MethodBase.GetCurrentMethod.Name & " Of " & Me.Name)
        End Try
    End Sub

    Private Sub frmInventoryAdjustment_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        Try

            Call SetImageControl(Me)
            Me.Icon = System.Drawing.Icon.FromHandle(CType(mdiMain.imgFormIcons.Images(2), Bitmap).GetHicon())
            Call GetAccessPermission(Me, "frmInventoryAdjustment")
            Call setPBRecords(Me, pbRecords)
            mblnActivate = True
            mblnChanged = False
          
        Catch ex As Exception
            MessageBox.Show(ex.Message, gstrMessage, MessageBoxButtons.OK, MessageBoxIcon.Error)
            AddErrorLog("Error " & Err.Number & " (" & Err.Description & ") in Procedure " & _
                Reflection.MethodBase.GetCurrentMethod.Name & " Of " & Me.Name)
        End Try
    End Sub

    Private Function blnSaveRecords() As Boolean
        Dim blnIsTransactionOpen As Boolean
        Dim strQuery As String = ""
        Dim intCtr As Integer
        Dim strIDs As String = ""
        Try
            blnSaveRecords = False


            grdDataEntry.EmbeddedNavigator.Buttons.DoClick(grdDataEntry.EmbeddedNavigator.Buttons.Append)

            If gdvDataEntry.HasColumnErrors = True Then
                Exit Function
            End If

            If (blnUnload = False) Then
                If (MessageBox.Show("Are you sure to add this adjustment details", "", MessageBoxButtons.YesNo, MessageBoxIcon.Question) = System.Windows.Forms.DialogResult.No) Then
                    gdvDataEntry.Focus()
                    Exit Function
                End If
            End If

            gtrnWebPlusMed = gconWebPlusMed.BeginTransaction
            blnIsTransactionOpen = True
            With gdvDataEntry

                '==== delete unused records  ====
                For intCtr = 0 To .RowCount - 2
                    If .GetRowCellValue(intCtr, "ID").ToString <> "" Then
                        If strIDs <> "" Then
                            strIDs = strIDs & ","
                        End If
                        strIDs = strIDs & .GetRowCellValue(intCtr, "ID")
                    End If
                Next intCtr
                If strIDs <> "" Then
                    Call DeleteFromTable("tblInventoryAdjustment", "DtDate='" & Format(CDate(dtFromDate.EditValue), gstrDtFormat) & "' and AdjustmentId not in (" & strIDs & ")")
                Else
                    Call DeleteFromTable("tblInventoryAdjustment", "DtDate='" & Format(CDate(dtFromDate.EditValue), gstrDtFormat) & "'")
                End If

                For intCtr = 0 To .RowCount - 2
                    If Val(.GetRowCellValue(intCtr, "Physical Qty").ToString) > 0 AndAlso Not IsDBNullOrNothing(.GetRowCellValue(intCtr, "Date")) Then
                        If Val(.GetRowCellValue(intCtr, "ID").ToString) = 0 Then
                            mlngRecordID = lngAutogeneratePrimaryKey("tblInventoryAdjustment", "AdjustmentId")
                            strQuery = mlngRecordID & _
                                         " , " & SmartReplace(Format(.GetRowCellValue(intCtr, "Date"), gstrDtFormat)) & _
                                         " ," & Val(.GetRowCellValue(intCtr, "Item Name").ToString) & _
                                         " , " & IIf(.GetRowCellValue(intCtr, "Type").ToString = "Deficit", 0, 1) & _
                                         ", " & Val(.GetRowCellValue(intCtr, "Physical Qty").ToString) & _
                                         " , " & SmartReplace(gstrUserName & "-" & Format(gdtCurrentDate, "dd-MMM-yyyy hh:mm:ss tt"))
                            Call InsertintoTable("tblInventoryAdjustment", strQuery)
                        Else
                            strQuery = "DtDate=" & SmartReplace(Format(.GetRowCellValue(intCtr, "Date"), gstrDtFormat)) & _
                                         " ,ItemId=" & Val(.GetRowCellValue(intCtr, "Item Name").ToString) & _
                                         " ,Type=" & IIf(.GetRowCellValue(intCtr, "Type").ToString = "Deficit", 0, 1) & _
                                         ",Qty=" & Val(.GetRowCellValue(intCtr, "Physical Qty").ToString) & _
                                         " ,LastModified=" & SmartReplace(gstrUserName & "-" & Format(gdtCurrentDate, "dd-MMM-yyyy hh:mm:ss tt"))

                            Call UpdateTable("tblInventoryAdjustment", strQuery, "AdjustmentId=" & .GetRowCellValue(intCtr, "ID"))
                        End If
                        Dim Qoh As Integer = Val(strRecordID("tblItem", "QOH", "ItemId=" & Val(.GetRowCellValue(intCtr, "Item Name").ToString)))
                        If Qoh < 0 Then
                            MessageBox.Show("After this transaction the stock will be negative.", gstrMessage, MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
                        End If
                    End If
                Next intCtr
            End With

            blnSaveRecords = True

            gtrnWebPlusMed.Commit()
            blnIsTransactionOpen = False

        Catch ex As Exception
            If blnIsTransactionOpen = True Then
                gtrnWebPlusMed.Rollback()
            End If
            If ex.Message.Contains("Negative") Then
                MessageBox.Show("After this transaction Stock will be Negative.", gstrMessage, MessageBoxButtons.OK, MessageBoxIcon.Warning)
            Else
                MessageBox.Show(ex.Message, gstrMessage, MessageBoxButtons.OK, MessageBoxIcon.Error)
                AddErrorLog("Error " & Err.Number & " (" & Err.Description & ") in Procedure " & _
                    Reflection.MethodBase.GetCurrentMethod.Name & " Of " & Me.Name)
            End If
        End Try
    End Function

    Private Sub btnSave_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnSave.Click
        Try
            If mblnChanged = False Then
                Exit Sub
            End If

            If blnSaveRecords() = False Then Exit Sub

            Call PopulateData()
        Catch ex As Exception
            pbRecords.Visible = False
            MessageBox.Show(ex.Message, gstrMessage, MessageBoxButtons.OK, MessageBoxIcon.Error)
            Call AddErrorLog("Error " & Err.Number & " (" & Err.Description & ") in Procedure " & _
                 Reflection.MethodBase.GetCurrentMethod.Name & " Of " & Me.Name)
        End Try
    End Sub

    Private Sub btnClose_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnClose.Click
        Me.Close()
    End Sub

    Private Sub gdvDataEntry_CellValueChanged(ByVal sender As Object, ByVal e As DevExpress.XtraGrid.Views.Base.CellValueChangedEventArgs) Handles gdvDataEntry.CellValueChanged
        mblnChanged = True
    End Sub

    Private Sub gdvDataEntry_InvalidRowException(ByVal sender As Object, ByVal e As DevExpress.XtraGrid.Views.Base.InvalidRowExceptionEventArgs) Handles gdvDataEntry.InvalidRowException
        e.ExceptionMode = DevExpress.XtraEditors.Controls.ExceptionMode.NoAction
    End Sub

    Private Sub gdvDataEntry_KeyDown(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles gdvDataEntry.KeyDown
        If gdvDataEntry.FocusedColumn Is gdvDataEntry.Columns("Physical Qty") AndAlso e.KeyCode = Keys.Enter Then
            If  Val(Trim(gdvDataEntry.GetRowCellValue(gdvDataEntry.FocusedRowHandle, "Item Name") & "")) <= 0 AndAlso IsDBNullOrNothing(gdvDataEntry.GetRowCellValue(gdvDataEntry.FocusedRowHandle, "Type")) AndAlso Val(Trim(gdvDataEntry.GetRowCellValue(gdvDataEntry.FocusedRowHandle, "Physical Qty") & "")) <= 0 Then
                btnSave.Focus()
            End If
        End If
    End Sub

    Private Sub gdvDataEntry_ShownEditor(ByVal sender As Object, ByVal e As System.EventArgs) Handles gdvDataEntry.ShownEditor
        Dim view As GridView = CType(sender, GridView)
        Try
            If view.FocusedColumn.FieldName = "Item Name" AndAlso TypeOf view.ActiveEditor Is GridLookUpEdit Then
                GLKEdit = CType(view.ActiveEditor, GridLookUpEdit)
                GLKEdit.Properties.DataSource = rpGlkItemName.DataSource
            End If
        Catch ex As Exception
            MessageBox.Show(ex.Message, gstrMessage, MessageBoxButtons.OK, MessageBoxIcon.Error)
            Call AddErrorLog("Error " & Err.Number & " (" & Err.Description & ") in Procedure " & _
                 Reflection.MethodBase.GetCurrentMethod.Name & " Of " & Me.Name)
        End Try
    End Sub

    Private Sub gdvDataEntry_ValidateRow(ByVal sender As Object, ByVal e As DevExpress.XtraGrid.Views.Base.ValidateRowEventArgs) Handles gdvDataEntry.ValidateRow
        Try
            Dim view As ColumnView = CType(sender, ColumnView)
            Dim colName As New GridColumn
            Dim blnError As Boolean
            If Val(gdvDataEntry.GetRowCellValue(e.RowHandle, "Item Name").ToString) <= 0 AndAlso IsDBNullOrNothing(gdvDataEntry.GetRowCellValue(e.RowHandle, "Type").ToString) AndAlso Val(gdvDataEntry.GetRowCellValue(e.RowHandle, "Physical Qty").ToString) <= 0 Then Exit Sub
            If IsDBNullOrNothing(gdvDataEntry.GetRowCellValue(e.RowHandle, "Date")) Then
                colName = view.Columns("Date") : blnError = True : view.SetColumnError(colName, "Specify Date")
            ElseIf Val(gdvDataEntry.GetRowCellValue(e.RowHandle, "Item Name").ToString) <= 0 Then
                colName = view.Columns("Item Name") : blnError = True : view.SetColumnError(colName, "Specify Item Name")
            ElseIf IsDBNullOrNothing(gdvDataEntry.GetRowCellValue(e.RowHandle, "Type")) Then
                colName = view.Columns("Type") : blnError = True : view.SetColumnError(colName, "Specify Type")
            ElseIf Val(gdvDataEntry.GetRowCellValue(e.RowHandle, "Physical Qty").ToString) <= 0 Then
                colName = view.Columns("Physical Qty") : blnError = True : view.SetColumnError(colName, "Specify Quantity")
            End If
            If blnError = True Then view.FocusedColumn = colName : e.Valid = False
        Catch ex As Exception
            MessageBox.Show(ex.Message, gstrMessage, MessageBoxButtons.OK, MessageBoxIcon.Error)
            Call AddErrorLog("Error " & Err.Number & " (" & Err.Description & ") in Procedure " & _
                 Reflection.MethodBase.GetCurrentMethod.Name & " Of " & Me.Name)
        End Try
    End Sub

    Private Sub GLKEdit_ParseEditValue(ByVal sender As Object, ByVal e As DevExpress.XtraEditors.Controls.ConvertEditValueEventArgs) Handles GLKEdit.ParseEditValue
        Try

            With gdvDataEntry
                If gdvDataEntry.FocusedColumn Is gdvDataEntry.Columns("Item Name") Then
                    If Not IsDBNullOrNothing(e.Value) And Not IsDBNullOrNothing(gdvDataEntry.GetFocusedRowCellValue("Item Name")) Then
                        ItemDetailsDataRow = CType(GLKEdit.Properties.View.GetDataRow(GLKEdit.Properties.View.FocusedRowHandle), DataRow)

                        If IsDBNullOrNothing(ItemDetailsDataRow) Then Exit Sub

                        If IsDBNullOrNothing(ItemDetailsDataRow.Item("ItemCode")) = False Then
                            .SetRowCellValue(.FocusedRowHandle, "Item#", ItemDetailsDataRow.Item("ItemCode"))
                        Else
                            .SetRowCellValue(.FocusedRowHandle, "Item#", DBNull.Value)
                        End If
                        If IsDBNullOrNothing(ItemDetailsDataRow.Item("ManufacturerName")) = False Then
                            .SetRowCellValue(.FocusedRowHandle, "Manufacturer", ItemDetailsDataRow.Item("ManufacturerName"))
                        Else
                            .SetRowCellValue(.FocusedRowHandle, "Manufacturer", DBNull.Value)
                        End If

                        If IsDBNullOrNothing(ItemDetailsDataRow.Item("Category")) = False Then
                            .SetRowCellValue(.FocusedRowHandle, "Category", ItemDetailsDataRow.Item("Category"))
                        Else
                            .SetRowCellValue(.FocusedRowHandle, "Category", DBNull.Value)
                        End If

                        If IsDBNullOrNothing(ItemDetailsDataRow.Item("QOH")) = False Then
                            .SetRowCellValue(.FocusedRowHandle, "Calculated Quantity", ItemDetailsDataRow.Item("QOH"))
                        Else
                            .SetRowCellValue(.FocusedRowHandle, "Calculated Quantity", DBNull.Value)
                        End If
                    Else
                        .SetRowCellValue(.FocusedRowHandle, "Item#", DBNull.Value)
                        .SetRowCellValue(.FocusedRowHandle, "Unit", DBNull.Value)
                        .SetRowCellValue(.FocusedRowHandle, "Unit Cost", DBNull.Value)
                        .SetRowCellValue(.FocusedRowHandle, "Calculated Quantity", DBNull.Value)
                    End If
                End If


            End With

        Catch ex As Exception
            MessageBox.Show(ex.Message, gstrMessage, MessageBoxButtons.OK, MessageBoxIcon.Error)
            Call AddErrorLog("Error " & Err.Number & " (" & Err.Description & ") in Procedure " & _
                 Reflection.MethodBase.GetCurrentMethod.Name & " Of " & Me.Name)
        End Try
    End Sub

    Private Sub btnCancel_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnCancel.Click
        Call btnFilter_Click(Nothing, Nothing)
    End Sub

    Private Sub btnFilter_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnFilter.Click
        Call PopulateData()
    End Sub

    Private Sub glkSelectItem_ButtonClick(ByVal sender As Object, ByVal e As DevExpress.XtraEditors.Controls.ButtonPressedEventArgs) Handles glkSelectItem.ButtonClick
        If e.Button.Index = 1 Then
            Call PopulateLookUpName()
        End If
    End Sub

    Private Sub chkDateRange_CheckedChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles chkDateRange.CheckedChanged
        If chkDateRange.Checked = True Then
            dtFromDate.Enabled = True
            dtToDate.Enabled = True
        ElseIf chkDateRange.Checked = False Then
            dtFromDate.Enabled = False
            dtToDate.Enabled = False
        End If
        Call btnFilter_Click(Nothing, Nothing)
    End Sub

    Private Sub rpGlkItemName_ButtonClick(ByVal sender As Object, ByVal e As DevExpress.XtraEditors.Controls.ButtonPressedEventArgs) Handles rpGlkItemName.ButtonClick
        If e.Button.Index = 1 Then
            Dim dsTemp As DataSet = FillDataSet("Select ItemId,ItemName,ItemCode,Category,ManufacturerName,QOH from vwItemDetails Order by ItemName")
            With rpGlkItemName
                .DataSource = dsTemp.Tables(0)
                .DisplayMember = "ItemName"
                .ValueMember = "ItemId"
                .NullText = ""
            End With
        End If
    End Sub

    Private Sub dtToDate_EditValueChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles dtToDate.EditValueChanged
        If Not IsDBNullOrNothing(dtToDate.EditValue) And mblnPopulateData = True Then
            Call btnFilter_Click(Nothing, Nothing)
        End If

    End Sub
    Private Sub dtFromDate_EditValueChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles dtFromDate.EditValueChanged
        If Not IsDBNullOrNothing(dtFromDate.EditValue) And mblnPopulateData = True Then
            Call btnFilter_Click(Nothing, Nothing)
        End If

    End Sub

    Private Sub glkSelectItem_EditValueChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles glkSelectItem.EditValueChanged
        If Not IsDBNullOrNothing(glkSelectItem.EditValue) And mblnPopulateData = True Then
            Call btnFilter_Click(Nothing, Nothing)
        End If

    End Sub

    Private Sub grdDataEntry_EmbeddedNavigator_ButtonClick(ByVal sender As System.Object, ByVal e As DevExpress.XtraEditors.NavigatorButtonClickEventArgs) Handles grdDataEntry.EmbeddedNavigator.ButtonClick
        If e.Button.ButtonType = NavigatorButtonType.Remove Then
            If (MessageBox.Show("Are you sure to delete this adjustment details", gstrMessage, MessageBoxButtons.YesNo, MessageBoxIcon.Question) = System.Windows.Forms.DialogResult.No) Then
                gdvDataEntry.Focus()
                Exit Sub
            End If
            Call DeleteFromTable("tblInventoryAdjustment", "AdjustmentId=" & mlngRecordID)
            Call PopulateData()
        End If
    End Sub
End Class
